import { Component, OnInit } from '@angular/core';
import {FormGroup, FormBuilder, Validators} from "@angular/forms";

@Component({
  selector: 'app-reactive01',
  templateUrl: './reactive01.component.html',
  styleUrls: ['./reactive01.component.less']
})
export class Reactive01Component implements OnInit {

  form: FormGroup;
  info: Organization = new Organization();
  validationMessage: OrganizationValidationMessage = new OrganizationValidationMessage();
  formErrors = {
    name: null,
    area: null,
    email: null,
    phone: null,
    address: null
  };

  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.initForm();
    this.form.valueChanges
      .subscribe(data => this.onValueChanged(data));
  }

  /*
   * 初始化响应式表单*/
  initForm() {
    if (!this.form) {
      this.form = this.fb.group({
        name: [null, [Validators.required]],
        area: [null, [Validators.required]],
        email: [null, [Validators.required]],
        phone: [null],
        address: [null]
      });
    }
  }

  onValueChanged(data?: any) {
    for (const field of Object.keys(this.validationMessage) ) {
      this.formErrors[field] = '';
      const ctrl = this.form.get(field);
      if (!!ctrl && ctrl.dirty && !ctrl.valid) {
        console.log(ctrl.errors);
        for (const errorKey of Object.keys(ctrl.errors)) {
          this.formErrors[field] += this.validationMessage[field][errorKey];
        }
      }
    }
  }

}

export class Organization {
  name: string;
  area: string;
  email: string;
  phone: string;
  address: string;
}
export class OrganizationValidationMessage {
  name = {
    minlength: '至少输入两位！',
    required: '名称不能为空！'
  };
}
